package br.com.skytef.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.http.HttpSession;

import br.com.skytef.entity.LoginEntity;
import br.com.skytef.entity.PosAutorizadoEntity;
import br.com.skytef.jdbc.ConnectionFactory;
import br.com.skytef.utils.utils;

public class loginDao {
	
	public Connection connection;

	@SuppressWarnings("static-access")
	public loginDao() {
		this.connection = new ConnectionFactory().getConnection();
	}

	public loginDao(HttpSession session) {
		this.connection = utils.recoverSessionDBConnection(session);
	}

	public loginDao(Connection con) {
		this.connection = con;
	}

	public Connection getConnection() {
		return connection;
	}
	
	
	/*--------------------------------------------------------------------------------------------------------
	 * Select
	 --------------------------------------------------------------------------------------------------------*/
	
	
	public LoginEntity selectbyUser(String name, String password) throws Exception {
		Connection connection = new ConnectionFactory().getConnection();
		LoginEntity result = null;
		try {
			PreparedStatement stmt = connection.prepareStatement(this.getQrySelectAll());
			stmt.setString(1, name);
			stmt.setString(2, password);
			result = this.execSelect(stmt);
			stmt.close();
			connection.close();	
		} catch (Exception e) {
			connection.close();
		}		
		return result;
	} 
	
	
	private LoginEntity execSelect(PreparedStatement stmt) throws Exception {
		LoginEntity login = new LoginEntity();

		try {
			ResultSet rs = stmt.executeQuery();
			if (rs.next()) {
				login.setId(rs.getInt("id"));
				login.setName(rs.getString("nome"));
				login.setLogin(rs.getString("login"));
				login.setPassword(rs.getString("senha"));
				login.setTipo(rs.getString("tipo"));
				login.setAtivo(rs.getString("ativo"));

			}
			rs.close();
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
		return login;
	}
	
	
	/*--------------------------------------------------------------------------------------------------------
	 * Query
	 --------------------------------------------------------------------------------------------------------*/
		
	
	private String getQrySelectAll() {

		StringBuffer sql = new StringBuffer();

		sql.append("SELECT * ");
		sql.append("FROM   usuario ");
		sql.append("WHERE  login = ? and senha = ? ; ");
		return sql.toString();

	}

}
